package dba.example.controllers

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{ModelAttribute, RequestMethod, RequestParam, RequestMapping}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.ModelMap
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction
import dba.example.common.DefaultPageable
import dba.example.entities.Company
import javax.validation.Valid
import org.springframework.validation.BindingResult
import dba.example.dao.CompanyDao

@Controller
@RequestMapping(Array("/company"))
class CompanyController @Autowired() (val dao: CompanyDao) {

  @RequestMapping(value = Array("/list"))
  def list(model: ModelMap, @RequestParam(defaultValue="0") pageNo: Int,
    @RequestParam(defaultValue="nameSort") sortColumn: String,
    @RequestParam(defaultValue="ASC") sortDirection: Direction) = {
    model.addAttribute("page", dao.list(new DefaultPageable(pageNo, 10, 0, new Sort(sortDirection, sortColumn))))
    model.addAttribute("sortColumn", sortColumn)
    model.addAttribute("sortDirection", sortDirection)
    "companyList"
  }

  @RequestMapping(value = Array("/view"))
  def view(@RequestParam id: Integer, model: ModelMap) = {
    model.addAttribute("company", dao.get(id))
    "companyView"
  }

  @RequestMapping(value = Array("/edit"))
  def edit(@RequestParam id: Integer, model: ModelMap) = {
    model.addAttribute("company", dao.get(id))
    "companyEdit"
  }

  @RequestMapping(value = Array("/add"))
  def add(model: ModelMap) = {
    model.addAttribute("company", new Company())
    "companyEdit"
  }

  @RequestMapping(value = Array("/save"), method = Array(RequestMethod.POST))
  def addContact(@Valid @ModelAttribute("company") company: Company, result: BindingResult) = {
    if (result.hasErrors()) {
      "companyEdit"
    }
    dao.save(company)
    "redirect:list"
  }

}
